<template>
 <div>
   <home-head/>
   <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <div class="wrap">
      <!-- 轮播 -->
          <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item v-for="banner in banners" :key="banner.id">
              <img :src="banner.picUrl" alt="">
            </van-swipe-item>
          </van-swipe>
        <!-- /轮播 -->

        <div class="wysmbox">
          <ul>
            <li>
              <a>
                <span>网易自营品牌</span>
              </a>
            </li>
            <li>
              <a>
                <span>30天无忧退换货</span>
              </a>
            </li>
            <li>
              <a>
                <span>48小时快速退款</span>
              </a>
            </li>
          </ul>
        </div>

        <!-- 宫格导航 -->
        <van-grid class="vangrid" :column-num="5" :gutter="6" :border="false" :clickable="true">
          <van-grid-item
          v-for="cate in cates"
          :key="cate.id"
          :to="{
            path: '/itemlist',
            query: {
              cateId: cate.id
            }
          }"
          :icon="cate.icon"
          :text="cate.name" />
          <van-grid-item icon="gem" text="nothing" />
        </van-grid>
        <!-- /宫格导航 -->

        <div class="wymnbox">
          <div class="newbox"></div>
          <div class="bjbox"></div>
        </div>

        <!-- 推荐商品 -->
        <van-list
            v-model="loading"
            :finished="finished"
            finished-text="靓仔没有更多了"
            @load="reachBottom"
          >
          <item-list :items="items" @clickItem="enterDetail" @clickItemcart="addCart"/>
        </van-list>
        <!-- /推荐商品 -->
    </div>
   </van-pull-refresh>
   <tabbar/>
 </div>
</template>

<script>
import Tabbar from '../../components/Tabbar.vue'
import HomeHead from './components/HomeHead.vue'
import ItemList from './components/Itemlist.vue'
import { fetchHomeBanner, fetchCates, fetchItems, addCart, fetchCartItems } from '_api'
import { getToken, isLogin } from '_utils'
import { Toast } from 'vant'
export default {
  name: 'Home',
  data () {
    return {
      banners: [],
      cates: [],
      items: [], // 推荐商品组件数据
      page: 1,
      pageSize: 5,
      loading: false,
      finished: false,
      isLoading: false
    }
  },
  created () {
    this.fetchBanners()
    this.fetchCates()
    this.fetchCartItems()
  },
  methods: {
    addCart (id) {
      // 加入购物车的动作 需要登录才能访问
      if (!isLogin()) {
        // 没有登录
        Toast.fail({
          message: '请登录',
          duration: 1000,
          onClose: () => {
            // 跳转到登录页
            this.$router.push({
              path: '/login',
              query: {
                from: '/home'
              }
            })
          }
        })
        return false
      }
      // 登录了 加入购物车
      addCart({
        goodsId: id,
        number: 1,
        token: getToken()
      }).then(res => {
        if (res.data.code === 2000) {
          Toast.fail('加入失败，请前往登录')
          this.$router.push('/login')
          return false
        }
        if (res.data.code === 0) {
          Toast.success('加入成功，请前往购买')
          this.$store.commit('cart/init_cart_info', {
            items: res.data.data.items,
            buyNumber: res.data.data.number
          })
        }
      })
    },
    fetchCartItems () {
      // 获取购物车数据
      fetchCartItems({
        token: getToken()
      }).then(res => {
        if (res.data.code === 0) {
          this.$store.commit('cart/init_cart_info', {
            items: res.data.data.items,
            buyNumber: res.data.data.number
          })
        }
      })
    },
    enterDetail (id) {
      // 跳转到详情页
      this.$router.push({
        path: 'Detail',
        query: {
          id
        }
      })
    },
    onRefresh () {
      // 上拉加载 初始化
      // 将数据清空
      this.items = []
      // 回到第一页
      this.page = 1
      // 将上拉加载到达底的状态变成false
      this.finished = false
      // 用户下拉刷新了
      this.fetchItems()
      this.page++
    },
    reachBottom () {
      // 上拉触底事件函数
      this.fetchItems()
      // 将page+1 请求下一页数据
      this.page++
    },
    fetchBanners () {
      fetchHomeBanner().then(res => {
        if (res.data.code === 0) {
          this.banners = res.data.data
        }
      })
    },
    fetchCates () {
      fetchCates().then(res => {
        if (res.data.code === 0) {
          this.cates = res.data.data
        }
      })
    },
    fetchItems () {
      fetchItems({
        categoryId: 72399,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        // 此次触底 请求完成 将、loading变成false 才能触发下次触底事件
        this.loading = false
        this.isLoading = false
        if (res.data.code === 0) {
          this.items = [
            ...this.items,
            ...res.data.data.result
          ]
        }
        if (res.data.code === 700) {
          // 已经到达最后一页
          this.finished = true
        }
      })
    }
  },
  components: { Tabbar, HomeHead, ItemList }
}
</script>

<style lang="scss" scoped>
.wrap{
  margin: 50px 0;
  .wysmbox{
    ul{
      display: flex;
      justify-content: space-around;
      li{
        font-size: 12px;
        line-height: 20px;
        margin-top: 10px;
      }
    }
  }
  .my-swipe{
    width: 100%;
    height: 175px;
    img{
      width: 100%;
    }
  }
  .wymnbox{
    width: 100%;
    height:135px;
    background-color: #EEEEEE;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    div{
      width: 45%;
      height: 128px;
    }
    .newbox{
      background-image: url('../../assets/img/new.webp');
      background-size: 100%;
    }
    .bjbox{
      background-image: url('../../assets/img/bj.webp');
      background-size: 100%;
    }
  }
}
</style>
